<template>
	<view class="dwu-picker">
		<view class="picker" @click="pickerShow">
			<u-input v-model="selectVal" inputAlign="right" border="none" :readonly="true" disabledColor="transparent" :disabled="disabled" :placeholder="placeholder"></u-input>
			<view class="arrow-down">
				<image src="@/static/news/arrow_right.png" mode=""></image>
			</view>
		</view>
		<u-picker :show="show" :columns="columns" :defaultIndex="defaultIndex" :keyName="keyName" @cancel="show = false" @confirm="confirm"></u-picker>
	</view>
</template>

<script>
	export default {
		name: "dwu-picker",
		props: {
			columns: {
				type: Array,
				default: []
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			defaultVal: {
				type: String,
				default: ''
			},
			keyVal: {
				type: String,
				default: 'type'
			},
			keyName: {
				type: String,
				default: 'label'
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			defaultVal(val) {
				this.setDefaultVal(val)
				// this.setDefaultIndex(val)
			}
		},
		data() {
			return {
				show: false,
				selectVal: '',
				defaultIndex: []
			};
		},
		methods: {
			pickerShow() {
				if (this.disabled) return
				this.show = true
			},
			setDefaultIndex(val) {
				this.defaultIndex = [val-1]
			},
			setDefaultVal(val) {
				let columns = this.columns[0]
				for (var i = 0; i < columns.length; i++) {
					if (columns[i][this.keyVal] == val) {
						this.selectVal = columns[i][this.keyName]
						this.defaultIndex = [i]
					}
				}
			},
			confirm(e) {
				console.log(e);
				this.selectVal = e.value[0][this.keyName]
				this.$emit('onconfirm', e)
				this.show = false
			}
		}
	}
</script>

<style lang="less">
	.dwu-picker {
		.picker {
			display: flex;
			align-items: center;

			.arrow-down {
				display: flex;
				align-items: center;
				image {
					width: 10rpx;
					height: 18rpx;
				}
			}
		}
	}
</style>